<template>
  <div class="cmsUploadFile" :class="disabled ? 'noneBtn' : ''">
    <el-upload
      class="upload-demo fill span18 small-payment-upload"
      :before-upload="(file) => uploadPartOne(file)"
      action
      :show-file-list="false"
      :file-list="list"
      :disabled="disabled"
    >
      <div>
        <el-button
          v-if="!disabled"
          size="small"
          :loading="isLoading"
          type="primary"
        >
          <i class="iconfont icon-shangchuan"></i> {{ buttonLabel }}
        </el-button>
      </div>
      <div slot="tip" v-if="!disabled" class="el-upload__tip">{{ info }}</div>
    </el-upload>
    <div class="file-list">
      <ul class="el-upload-list el-upload-list--picture-card">
        <li
          v-for="(item, index) in list"
          :key="index"
          :tabindex="index"
          class="el-upload-list__item is-ready"
        >
          <div :id="'c_' + item.id" style="height: 100%">
            <div v-if="notImage(item)" class="file-name">
              {{ item.realName }}
            </div>
            <img
              v-else
              :id="'img_' + item.id"
              alt=""
              class="el-upload-list__item-thumbnail"
            />
            <span class="el-upload-list__item-actions">
              <span
                v-if="showPreview"
                class="el-upload-list__item-preview"
                @click="preview(item)"
              >
                <i class="el-icon-zoom-in"></i>
              </span>
              <span class="el-upload-list__item-delete" @click="download(item)">
                <i class="el-icon-download"></i>
              </span>
              <span
                class="el-upload-list__item-delete"
                v-if="!disabled"
                @click="removeFile(item)"
              >
                <i class="el-icon-delete"></i>
              </span>
            </span>
          </div>
        </li>
      </ul>
    </div>

    <el-dialog :visible.sync="dialogVisible" append-to-body :fullscreen="true">
      <img width="100%" height="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import { v4 as uuidv4 } from "uuid";
import msgUtil from "@/utils/msgUtil";
import Util from "@/utils/publicUpload";

export default {
  name: "UploadFile",
  props: {
    imgData: {
      type: String,
      default: "",
    },
    fileList: {
      type: Array,
      default: () => [],
    },
    fileSystem: {
      type: Object,
      default: () => {
        return { sys: "", module: "", part: "" };
      },
    },
    type: {
      type: Boolean,
      default: false,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    info: {
      type: String,
      default: "",
    },
    buttonLabel: {
      type: String,
      default: "点击上传",
    },
    //文件類型校验方法-若需要校验，从父组件传入此方法
    checkFiles: {
      type: Function,
      default: (file) => {
        return true;
      },
    },
    //获取文件后的回调函数-从父组件传入此方法
    getFilesCb: {
      type: Function,
      default: () => {},
    },
    //获取文件后的回调函数-从父组件传入此方法
    uploadCb: {
      type: Function,
      default: () => {},
    },
    showPreview: {
      type: Boolean,
      default: true,
    },
  },
  watch: {
    
 
    fileList: {
      handler(val) {
        this.list = [...val];
      },
      deep: true,
    },
  },
  data() {
    return {

      isLoading: false,
      dialogImageUrl: "",
      dialogVisible: false,
      list: [],
      images: [],
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
    if(!this.imgData){
      return false
    }
    this.list = [];
    for(let item of this.imgData.split(",")){
        Util.getFileById(item).then((res) => {
        const items = res.data 
          this.list.push({
            realName: items.name,
            name: items.name,
            size: items.size,
            ext: items.ext,
            id: items.id,
          });
        this.setImg();
      });

    }
    
    },
    setImg() {
      this.list.forEach((file) => {
        Util.preView(file.id).then((data) => {
          document.getElementById("img_" + file.id).src = data;
          file.src = data;
        });
      });
    },
    setLastImg() {
      const file = this.list[this.list.length - 1];
      const div = document.getElementById("c_" + file.id);
      Util.preView(file.id).then((url) => {
        const child = div.querySelector("div");
        if (child) {
          div.removeChild(child);
        }
        const img = document.createElement("img");
        img.id = "img_" + file.id;
        img.className = "el-upload-list__item-thumbnail";
        img.src = url;
        div.appendChild(img);
      });
    },
    uploadPartOne(file) {
      this.beforeUpload(file, this.fileSystem.part);
      return false;
    },
    // 上传文件前
    beforeUpload(file, part) {
      if (!this.checkFiles(file)) {
        return;
      }
      /*
       *公共上传方法
       * */
      this.$set(this, "isLoading", true);
  
     
      this.$store.state.settings.uploadLoading = false;
      Util.uploadFile(file, "", this.fileSystem.module, part, file.name)
        .then(async (res) => {
          if (res.code === 200) {
            if (!this.type) {
              if (this.list.length != 0) {
                //先解绑
                Util.removeFile(this.list[0].id);
                this.list = [
                  {
                    realName: file.name,
                    name: file.name,
                    size: file.size,
                    ext: file.ext,
                    id: res.data[0],
                  },
                ];
              } else {
                this.list = [
                  {
                    realName: file.name,
                    name: file.name,
                    size: file.size,
                    ext: file.ext,
                    id: res.data[0],
                  },
                ];
              }
            }
            if (this.type) {
              this.list.push({
                realName: file.name,
                name: file.name,
                size: file.size,
                ext: file.ext,
                id: res.data[0],
              });
            }
            this.uploadCb(res);
            this.$nextTick(() => {
              this.setLastImg();
            });
          } else {
            msgUtil.error2(res.data.message);
          }
          this.change();
        })
        .catch((res) => {
          this.$set(this, "isLoading", false);
          this.$store.state.settings.uploadLoading = true;
          msgUtil.error2("上传文件前-请求失败!");
        })
        .finally(() => {
          this.$set(this, "isLoading", false);
          this.$store.state.settings.uploadLoading = true;
        });
    },
    // 删除文件时解绑文件
    removeFile(file) {
      this.list.forEach((item, index) => {
        if (file.id === item.id) {
          this.list.splice(index, 1);
        }
      });
      Util.removeFile(file.id).then(() => {
        this.change();
      });
    },
    download(file) {
      Util.checkFile(file.id, file.realName);
    },
    change() {
      this.$emit("change", this.list);
    },
    notImage(item) {
      if (
        item.ext == "jpg" ||
        item.ext == "jpeg" ||
        item.ext == "png" ||
        item.ext == "gif"
      ) {
        return false;
      }
      return true;
    },
    preview(file) {
      if (file.src) {
        this.$nextTick(() => {
          this.dialogImageUrl = file.src;
        });
      } else {
        const id = "img_" + file.id;
        const img = document.getElementById(id);

        this.dialogImageUrl = img.src;
      }
      this.dialogVisible = true;
    },
    uuid() {
      return uuidv4().split("-")[0];
    },
  },
};
</script>

<style scoped lang="scss">
.cmsUploadFile {
  width: 100%;
  .fileList {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .fileName {
      display: flex;
      align-items: center;
      cursor: pointer;
      span {
        display: block;
        width: 247px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
  }
}
.file-name {
  text-align: center;
  line-height: 140px;
}
.file-list {
  width: 100%;
}
</style>
<style lang="scss">
.noneBtn {
  .small-payment-upload {
    display: none;
  }
}
</style>
